package com.club325.voicemicroblog.persist;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

import com.club325.voicemicroblog.database.hibernateutil.HibernateUtil;
import com.club325.voicemicroblog.domain.PrivateInfo;
import com.club325.voicemicroblog.domain.User;

public class PermissionControllerImplement implements PermissionControllerUtil {
	public PrivateInfo thePrivateInfo;
	public User theUser;

	public PermissionControllerImplement() {

	}

	/**
	 * @return java.lang.String
	 */
	public String getPassword(String UserID) {
		if(UserID == null)
			return null;
		
		try
		{
			Criteria crit = HibernateUtil.getSession().createCriteria(User.class);
			crit.add(Restrictions.eq("UserID", UserID));
			User u = (User) crit.uniqueResult();
			return u.getPassword();
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * @param UserID
	 * @param Password
	 * @return java.lang.Boolean
	 */
	public Boolean Login(String UserID, String Password) {
		if((UserID == null)||(Password == null))
		{
			return false;
		}
		
		User u;
		try {
			Criteria crit = HibernateUtil.getSession().createCriteria(
					User.class);
			crit.add(Restrictions.eq("UserID", UserID));
			u = (User) crit.uniqueResult();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		if (u == null)
			return false;
		if (u.getPassword().equals(Password)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * @param UserID
	 * @param PrivateInfo
	 * @return java.lang.Boolean
	 */
	public Boolean UserRegister(User UserID, PrivateInfo Info) {
		if ((UserID == null) || (Info == null) || 
				(!Info.getUserID().equals(UserID.getUserID())))
		{
			return false;
		}

		try {
			HibernateUtil.add(UserID);
			HibernateUtil.add(Info);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	public boolean isAdmintrator(String UserID) {
		if(UserID == null)
		{
			return false;
		}
		
		try
		{
			Criteria crit = HibernateUtil.getSession().createCriteria(User.class);
			crit.add(Restrictions.eq("UserID", UserID));
			User u = (User)crit.uniqueResult();
			if(u == null)
				return false;
			if(u.getPermission() == 1)
				return true;
			else
				return false;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return false;
		}
	}
}
